<template>
  <div class="address_list">
    <van-nav-bar @click-left="$router.go(-1)" left-arrow title="收货地址"/>

    <van-address-list v-model="chosenAddressId" :list="addressList" :switchable="true" @edit="editAddress"
                      default-tag-text="默认" @select="selectAddress">
    </van-address-list>

    <div class="btn_Container">
      <van-button color="linear-gradient(to right, #580C59, #8389E0)" class="btn" round @click="addAddress">
        添加
      </van-button>
    </div>
  </div>
</template>

<script>
import jwt_decode from "jwt-decode";

export default {
  name: "AddressList",

  data() {
    return {
      chosenAddressId: "1",
      addressList: [],
      type: this.$route.query.type,
      count: this.$route.query.count
    }
  },

  created() {
    if (localStorage.getItem("selectAddress")) {
      this.chosenAddressId = JSON.parse(localStorage.getItem("selectAddress"))
    } else {
      this.getDefaultAddress();
    }
    this.getAddressList();

  },

  mounted() {
    let height = document.documentElement.clientHeight || document.body.clientHeight;
    let htmlDom = document.getElementsByClassName("address_list")[0];
    htmlDom.style.height = height + "px";
  },

  methods: {
    //获取地址列表数据
    async getAddressList() {
      let token = jwt_decode(localStorage.getItem("eleToken"));
      let res = await this.$axios.post(this.$api.getAddressList, {userId: token.userId});
      if (res.status === 200 && res.data.code === 200) {
        this.addressList = res.data.data;
      } else {
        this.$notify(res.data.message);
      }
    },

    // 获取默认地址
    async getDefaultAddress() {
      let userId = jwt_decode(localStorage.getItem("eleToken")).userId;
      let res = await this.$axios.post(this.$api.getDefaultAddress, {userId: userId});
      if (res.status === 200 && res.data.code === 200) {
        this.chosenAddressId = res.data.data.id
      } else {
        this.$notify(res.data.message);
      }
    },

    addAddress() {
      this.$router.push({path: "/address/edit", query: {type: 0}});
    },

    editAddress(item) {
      this.$router.push({path: "/address/edit", query: {type: 1, id: item.id}});
    },

    selectAddress(item) {
      localStorage.removeItem("selectAddress");
      localStorage.setItem("selectAddress", item.id);
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="less" scoped>

.address_list {
  background-color: #fafafa;

  .van-address-list__bottom {
    visibility: hidden;
  }

  .btn_Container {
    position: fixed;
    bottom: 30px;
    width: 100%;

    .btn {
      width: 80%;
      margin-left: 10%;
    }
  }
}

</style>
